Skip to main content

Ether Transactions

Sending transactions is really simple with useDApp. All we need to send a simple transaction, is to use useSendTransaction hook, which returns a sendTransaction function and state object.

See Transaction Status for reference on how to monitor the state of a transaction.

You can add additional buffer of gas limit by setting gasLimitBufferPercentage in config or directly in transaction options, see live example below. It adds 10% of gas limit more to what is estimated by the Ethers library.

Example

Simply call a hook in a component.

  const { sendTransaction, state } = useSendTransaction()

Then when you want to send a transaction, call sendTransaction for example in a button callback. Function accepts a Transaction Request object as a parameter. In example below setDisabled(true) sets input components to disabled while transaction is being processed (It is a good practice to disable component when transaction is mining).

  const handleClick = () => {
setDisabled(true)
sendTransaction({ to: address, value: utils.parseEther(amount) })
}

Live example

App will send 1 wei to a test account. Connect a MetaMask wallet and switch to a test network, such as Kovan or Ropsten.

App.tsx
import React from 'react'
import ReactDOM from 'react-dom'
import { DAppProvider, useSendTransaction, useEthers, Config, Goerli, Kovan, Rinkeby, Ropsten } from '@usedapp/core'
import { getDefaultProvider } from 'ethers'
import { MetamaskConnect } from './components/MetamaskConnect'

const config: Config = {
readOnlyChainId: Goerli.chainId,
readOnlyUrls: {
[Goerli.chainId]: getDefaultProvider('goerli'),
[Kovan.chainId]: getDefaultProvider('kovan'),
[Rinkeby.chainId]: getDefaultProvider('rinkeby'),
[Ropsten.chainId]: getDefaultProvider('ropsten'),
},
gasLimitBufferPercentage: 10, // The percentage by which the transaction may exceed the estimated gas limit.
}

ReactDOM.render(
<DAppProvider config={config}>
<App />
</DAppProvider>,
document.getElementById('root')
)

export function App() {
const { chainId, account } = useEthers()
const { sendTransaction, state } = useSendTransaction()

if (!config.readOnlyUrls[chainId]) {
return <p>Please use either Goerli, Kovan, Rinkeby or Ropsten testnet.</p>
}
const status = state.status
const address = '0xe13610d0a3e4303c70791773C5DF8Bb16de185d1'

const send = () => {
void sendTransaction({ to: address, value: 1 })
}

const WalletContent = () => (
<div>
<button onClick={() => send()}>Send ether</button>
<p>Status: {status}</p>
</div>
)

return (
<div>
<MetamaskConnect />
{account && <WalletContent />}
</div>
)
}